import React, { useState, useEffect, useRef } from "react";
import { Stack, useNavigationContainerRef } from "expo-router";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { router } from "expo-router";
import TokenManager from "@/utils/token-utils";
import { MenuProvider as PopupMenuProvider } from "react-native-popup-menu";
import { ThemeProvider, useTheme } from "@/contexts/ThemeContext";
import { AuthProvider } from "@/contexts/AuthContext";
import { StatusBar } from "expo-status-bar";
import { KeyboardProvider } from "react-native-keyboard-controller";
import AlertComponent from "@/components/Global/Alert";
import AlertService from "@/components/Global/Alert/service";
import { AlertRefType } from "@/components/Global/Alert/types";
// 开发构建
import "expo-dev-client";
// import { useReactNavigationDevTools } from "@dev-plugins/react-navigation";

function NavigationContent() {
  const { activeTheme, colors } = useTheme();

  // region devtools开发者工具
  const navigationRef = useNavigationContainerRef();
  //   useReactNavigationDevTools(navigationRef);
  // endregion

  return (
    <KeyboardProvider>
      <StatusBar
        style={activeTheme === "dark" ? "light" : "dark"}
        backgroundColor={colors.background}
      />
      <PopupMenuProvider>
        <Stack
          screenOptions={{
            headerTitleAlign: "center",
            headerTintColor: colors.text.primary,
            headerTitleStyle: {
              fontWeight: "600",
              fontSize: 18,
            },
            headerStyle: {
              backgroundColor: colors.background,
            },
          }}
        >
          <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
          <Stack.Screen name="scan" options={{ headerShown: false }} />
          <Stack.Screen name="chat" options={{ headerShown: false }} />
          <Stack.Screen name="login" options={{ headerShown: false }} />
          <Stack.Screen name="media" options={{ headerShown: false }} />
          <Stack.Screen name="qrcode" options={{ headerShown: false }} />
          <Stack.Screen name="contact" options={{ headerShown: false }} />
          <Stack.Screen name="search" options={{ headerShown: false }} />
          <Stack.Screen name="friend" options={{ headerShown: false }} />
          <Stack.Screen name="groupchat" options={{ headerShown: false }} />
        </Stack>
      </PopupMenuProvider>
    </KeyboardProvider>
  );
}

export default function Layout() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const alertRef = useRef<AlertRefType | null>(null);

  useEffect(() => {
    if (alertRef.current) {
      AlertService.setAlertRef(alertRef);
    }
    const checkUserToken = async () => {
      const userToken = await TokenManager.getToken(); // 确保异步获取
      const newIsLoggedIn = !!userToken;
      setIsLoggedIn(newIsLoggedIn); // 更新状态

      // 根据登录状态进行路由跳转
      if (!newIsLoggedIn) {
        // 如果未登录，则跳转到登录页
        router.replace("/login");
      }
    };

    checkUserToken();
    // 依赖项为空，此 effect 仅在组件挂载时运行
  }, []);

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <ThemeProvider>
        <AuthProvider>
          <AlertComponent
            style={{
              position: "absolute",
              top: 30,
              left: 0,
              right: 0,
              zIndex: 9999,
              marginHorizontal: 20,
            }}
            duration={4000}
            ref={alertRef}
          />
          <NavigationContent />
        </AuthProvider>
      </ThemeProvider>
    </GestureHandlerRootView>
  );
}
